import React, { PureComponent } from 'react'

export class App extends PureComponent {
  constructor() {
    super()
    this.state = {
      books: [
        {
          name: 'JS高级设计',
          count: 12,
          price: 99
        },
        {
          name: 'Vue高级设计',
          count: 1,
          price: 67
        },
      ]
    }
  }
  addBook() {
    let newBook = {
      name: 'React高级设计',
      count: 1,
      price: 33
    }
    // 1. 直接修改原有的state，重新设置一遍
    // 在PureComponent中是不能引入重新渲染（re-render）
    // this.state.books.push(newBook)
    // this.setState({ bookes: this.state.books })

    // 2. 复制一份books，在新的books中修改，并设置新的books
    let newBooks = [...this.state.books]
    newBooks.push(newBook)
    this.setState({ books: newBooks })
  }
  addCounter(index) {
    let books = [...this.state.books]
    books[index].count++
    this.setState({ books })
  }
  render() {
    const { books } = this.state
    return (
      <div>
        App
        <ul>
          {
            books.map((item, index) => {
              return <li key={index}>
                <span>name:{ item.name } - price: { item.price } - count: { item.count }</span>
                <button onClick={() => this.addCounter(index)}>+1</button>
              </li>
            })
          }
        </ul>
        <button onClick={e => this.addBook(e)}>增加书籍</button>
      </div>
    )
  }
}

export default App